<template>
  <div ref="wrapper" class="c-n-marquee">
    <div ref="text"
      class="box-container"
      :style="{ 'left': textLeft }"
      @mouseenter="parse = true"
      @mouseleave="parse = false">
      <slot></slot>
    </div>
  </div>
</template>
<script>
export default {
  name: 'NMarquee',
  props: {
    delay: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      textLeft: '',
      parse: null
    }
  },
  mounted() {
    this.marquee()
  },
  methods: {
    marquee() {
      const _this = this
      const wrapperWidth = this.$refs.wrapper.clientWidth // 容器的总宽度
      const lis = this.$refs.text.childNodes

      let timer
      let textWidth = 6 // 文本的总宽度
      lis.forEach(ret => {
        textWidth += ret.clientWidth
      })
      this.$refs.text.style.width = textWidth + 'px'
      this.textLeft = 1 + 'px' // 开始滚动前设定文本在容器最左侧以内

      setTimeout(() => {
        textRoll()
      }, this.delay)

      function textRoll() {
        // 轮完
        if (parseInt(_this.textLeft) < -textWidth) {
          _this.textLeft = wrapperWidth + 'px'
        }
        // 悬停暂停
        if (!_this.parse) {
          _this.textLeft = parseInt(_this.textLeft) - 1 + 'px' // 向容器最左移动
        }
        if (timer) clearTimeout(timer)
        timer = setTimeout(() => {
          textRoll()
        }, 10)
      }
    }
  }

}
</script>
